package com.marktotop.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.marktotop.pojo.Order;
import com.marktotop.pojo.SeckillOrder;
import com.marktotop.pojo.User;
import com.marktotop.response.ResultCode;
import com.marktotop.service.IGoodsService;
import com.marktotop.service.IOrderService;
import com.marktotop.service.ISeckillOrderService;
import com.marktotop.vo.GoodsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * SecKillController
 *
 * @author WXLD
 * @Data 2021/6/19
 * @Since 1.0
 */
@Controller
@RequestMapping("/seckill")
public class SecKillController {

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private  ISeckillOrderService seckillOrderService;

    @Autowired
    private IOrderService orderService;

    /**
     * 秒杀功能
     *      未登录判断
     *       1、有库存
     *       2、每个用户只能秒杀一件商品，避免重复下单
     *
     * @param model
     * @param user
     * @param goodsId
     * @return
     */
    @RequestMapping("/doSeckill")
    public String doSecKill(Model model, User user,Long goodsId){
        // 判断是否登录
        if (null == user){
            return "login";
        }
        model.addAttribute("user",user);
        // 判断是否有库存
        GoodsVO goods = goodsService.findDetailByGoodsId(goodsId);
        if(goods.getStokeCount() < 1){
            model.addAttribute("errMsg", ResultCode.GOODS_STOCK_EMPTY.getMessage());
            return "secKillFail";
        }
        // 判断订单表,是否重复抢购
        SeckillOrder seckillOrder = seckillOrderService.getOne(
                new QueryWrapper<SeckillOrder>()
                        .eq("user_id", user.getId())
                        .eq("goods_id", goodsId));
        if (seckillOrder != null){
            model.addAttribute("errMsg", ResultCode.REPEAT_ORDER.getMessage());
            return "secKillFail";
        }
        // 秒杀下单
        Order order = orderService.seckill(user,goods);
        model.addAttribute("order",order);
        model.addAttribute("goods",goods);
        return "orderDetail";
    }
}
